package yogiro.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import yogiro.service.TourInfoService;
import yogiro.to.CommentTO;
import yogiro.to.ListTO;
import yogiro.to.MapTO;
import yogiro.to.MemberTO;
import yogiro.to.PagingTO;
import yogiro.to.PictureTO;
import yogiro.to.RecommendTO;
import yogiro.to.TourInfoTO;
import yogiro.util.Utilities;

public class TourInfoController extends MultiActionController{
	
	private TourInfoService service;
	public TourInfoController(TourInfoService service){
		this.service = service;
	}
	//여행정보 사진.글 등록
	public ModelAndView insertTourInfo(HttpServletRequest request, HttpServletResponse response, TourInfoTO tio) throws Exception{
		ModelAndView mv = null;
		HttpSession session = request.getSession();
		String tourTitle = request.getParameter("tourTitle");
		String tourContent = request.getParameter("tourContent");
		HashMap map = new HashMap();
		MemberTO member = (MemberTO) session.getAttribute("mto");
		String tourWriter = member.getMemberName();
		String tourWriterType = String.valueOf(member.getMemberLevel());
		//지도 위도, 경도 받아오기
		String latLong = request.getParameter("lngt");
		Double lng = Double.parseDouble(latLong.substring(0,11));
		Double lat = Double.parseDouble(latLong.substring(12));
		
		//
		tio = new TourInfoTO(tourTitle, tourContent, tourWriter, tourWriterType);
		service.insertTourInfo(tio);
		
		int tourNo=tio.getTourNo();
		MapTO mto = new MapTO(lng, lat, tourNo);
		
		service.insertMap(mto);
		int pictureGroup = tio.getTourNo();
		
		
		String fileName = request.getParameter("fileName");
		PictureTO pto = new PictureTO(fileName, pictureGroup);
		service.pictureUp(pto);
		ArrayList<PictureTO> ptoList = new ArrayList<PictureTO>();
		ptoList.add(pto);
		String fileName1 = request.getParameter("fileName1");
		if(!fileName1.equals("")&&fileName1!=null){
		pto = new PictureTO(fileName1, pictureGroup);
		service.pictureUp(pto);
		ptoList.add(pto);
		}
		String fileName2 = request.getParameter("fileName2");
		if(!fileName2.equals("")&&fileName2!=null){
				pto = new PictureTO(fileName2, pictureGroup);
		service.pictureUp(pto);
		ptoList.add(pto);
		}
		
		String fileName3 = request.getParameter("fileName3");
		if(!fileName3.equals("")&&fileName3!=null){
		pto = new PictureTO(fileName3, pictureGroup);
		service.pictureUp(pto);
		ptoList.add(pto);
		}
		
		String fileName4 = request.getParameter("fileName4");
		if(!fileName4.equals("")&&fileName4!=null){
		pto = new PictureTO(fileName4, pictureGroup);
		service.pictureUp(pto);
		ptoList.add(pto);
		}
		System.out.println(fileName);
		System.out.println(fileName1);
		System.out.println(fileName2);
		System.out.println(fileName3);
		System.out.println(fileName4);
		map.put("pto", ptoList);
		map.put("tio", tio);
		map.put("mto", mto);
		mv = new ModelAndView("tour_info/Tour_Show", "map", map);	
		return mv; 
	}
	
	//메인에 보여질 여행게시물 추천수 높은순으로 3개
	public ModelAndView selectTourRecommend(HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView mv = null;
		String tourWriterType = "0";
		ArrayList list = service.selectTourRecommend(tourWriterType);
		ArrayList list1 = new ArrayList();
		for(int i=0;i<list.size();i++){
			TourInfoTO tio = (TourInfoTO) list.get(i);
			list1.add(service.selectTourRecommend2(tio.getTourNo()));
		}
		ListTO listTo = new ListTO(list, list1);
		
		mv = new ModelAndView("tour_info/Tour_main", "list", listTo);	
		return mv;
	}
	
	//여행게시판 전체 리스트(페이징)
	public ModelAndView selectTourList(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String pageTmp = request.getParameter("page");
		int page = 1;
		try{
			page = Integer.parseInt(pageTmp);
		}catch(Exception e){}
		
		ModelAndView mv = null;
		
			ArrayList<TourInfoTO> tourList = service.selectTourListByPage(page);
			ArrayList<PictureTO> picList = new ArrayList<PictureTO>();
			for(int i=0;i<tourList.size();i++){
				TourInfoTO tio = (TourInfoTO) tourList.get(i);
				tio.setTourWritedate(Utilities.changeDayFormat(tio.getTourWritedate()));
				PictureTO pto = service.selectTourRecommend2(tio.getTourNo());
				picList.add(pto);
			}
			int totalContent = service.selectTotalContent();
			PagingTO pagingTO = new PagingTO(totalContent, page);
			ListTO lto = new ListTO(tourList, picList, pagingTO);
			mv = new ModelAndView("tour_info/Tour_List", "lto", lto);
		return mv;
	}

	//여행정보 게시글 쓰기에서 사진 미리보기
	public ModelAndView pictureUp(HttpServletRequest request, HttpServletResponse response, PictureTO pto) throws Exception{
		String path = getServletContext().getRealPath("/img");
		List list = pto.getUpPicture();
		String [] fileNames = new String[list.size()];
		int i = 0;
		String originalName = "";
		for(Object obj : list){
			MultipartFile file = (MultipartFile)obj;
			String fileName = file.getOriginalFilename();
			if(!file.isEmpty()){
				fileNames[i++]=fileName;
				File f = new File(path,fileName);
				file.transferTo(f);
				originalName+=fileName;
			}
		}
		JSONArray arr =new JSONArray(fileNames);
		HashMap map = new HashMap();
		map.put("fileName", arr);
		//return new ModelAndView("jsonView", "ajaxData", map);
		return new ModelAndView("ajaxView", "ajaxData", new JSONObject(map).toString());
	
	}
	//여행정보 작성후, 리스트 클릭시 보여질 여행정보글 화면
	public ModelAndView tourShow(HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView mv = null;
		HashMap map = new HashMap();
		
			int tourNo = Integer.parseInt(request.getParameter("tourNo"));
			//2. Business Logic 요청 - Model
			TourInfoTO tio = service.getContentByTourNO(tourNo);
			ArrayList<PictureTO> pto = service.selectTourRecommend3(tourNo);
			ArrayList<CommentTO> cto = service.selectAllComment(tourNo);
			MapTO mto = service.selectMapByTourNo(tourNo);
			map.put("tio", tio);
			map.put("pto", pto);
			map.put("cto", cto);
			map.put("mto", mto);
			
			mv = new ModelAndView("tour_info/Tour_Show", "map", map);
		return mv;
	}
	//글쓰기 누르면 보여질 여행글쓰기 폼(tiles)
	public String tourWrite(HttpServletRequest request, HttpServletResponse response){
		String re = null;
			re = "tour_info/Tour_Write";
		return re;//viewName - 타일즈설정 <definition>의 name속성 값을 return
	}
	
	//여행정보 게시판 글 수정폼 가기
	public ModelAndView getModifyTourInfo(HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView mv = null;
		HashMap map = new HashMap();
			int tourNo = Integer.parseInt(request.getParameter("tourNo"));
			//2. Business Logic 요청 - Model
			TourInfoTO tio = service.getContentByTourNO(tourNo);
			tio.setTourContent(Utilities.changeContentForTextArea(tio.getTourContent()));
			ArrayList<PictureTO> pto = service.selectTourRecommend3(tourNo);
			ArrayList<CommentTO> cto = service.selectAllComment(tourNo);
			MapTO mto = service.selectMapByTourNo(tourNo);
			map.put("tio", tio);
			map.put("pto", pto);
			map.put("cto", cto);
			map.put("mto", mto);
			mv = new ModelAndView("tour_info/Tour_Modify", "map", map);
		
		return mv;
	}
	//여행정보 수정확인
	public ModelAndView showModifyTourInfo(HttpServletRequest request, HttpServletResponse response, TourInfoTO tio) throws Exception{
		ModelAndView mv = null;
		int tourNo = Integer.parseInt(request.getParameter("tourNo"));
		String tourTitle = request.getParameter("tourTitle");
		String tourContent = request.getParameter("tourContent");
		HashMap map = new HashMap();
		HttpSession session = request.getSession();
		MemberTO member = (MemberTO) session.getAttribute("mto");
		//지도 위도, 경도 받아오기
		String latLong = request.getParameter("lngt");
		Double lng = Double.parseDouble(latLong.substring(0,11));
		Double lat = Double.parseDouble(latLong.substring(12));
		
		//
		tio = new TourInfoTO(tourNo, tourTitle, tourContent);
		service.updateContent(tio);
		int mapGroup = tourNo;
		MapTO mto = new MapTO(lng, lat, mapGroup);
		
		service.updatemap(mto);
		int pictureGroup = tourNo;
		String fileName = request.getParameter("fileName");
		int pictureNo = Integer.parseInt(request.getParameter("pictureNo"));
		PictureTO pto = new PictureTO(pictureNo, fileName, pictureGroup);
		service.updatePicture(pto);
		
		tio = service.getContentByTourNO(tourNo);
		ArrayList<PictureTO> pto1 = service.selectTourRecommend3(tourNo);
		ArrayList<CommentTO> cto = service.selectAllComment(tourNo);
		mto = service.selectMapByTourNo(tourNo);
		map.put("tio", tio);
		map.put("pto", pto1);
		map.put("cto", cto);
		map.put("mto", mto);
		mv = new ModelAndView("tour_info/Tour_Show", "map", map);
		return mv;
	}
	
	//여행정보 게시판 글 삭제
	public ModelAndView deleteTourInfo(HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView mv = null;
		int tourNo = Integer.parseInt(request.getParameter("tourNo"));
		String page = request.getParameter("page");
		System.out.println(page);
		int pictureGroup = tourNo;
		int mapGroup = tourNo;
		service.deleteMapTourNO(mapGroup);
		service.deletePictureTourNO(pictureGroup);
		service.deleteCommentByTourNO(tourNo);
		service.deleteContentTourNO(tourNo);
		mv = new ModelAndView("tourinfo.do?method=selectTourList", "page", page);
		return mv;
	}
	
	//여행정보 추천
	public ModelAndView recommendTourInfo(HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView mv = null;
		HashMap map = new HashMap();
		HttpSession session = request.getSession();
		MemberTO member = (MemberTO) session.getAttribute("mto");
		String memberId = member.getMemberId();
		int tourNo = Integer.parseInt(request.getParameter("tourNo"));
		RecommendTO rto = new RecommendTO(memberId, tourNo);
		map.put("recommendId", memberId);
		map.put("recommendTourNo", tourNo);
		int cnt = service.selectRecommend(map);
		if(cnt==0){
			service.insertRecommend(rto);
			service.updateRecommend(tourNo);
			TourInfoTO tio = service.getContentByTourNO(tourNo);
			map.put("rect", "추천되었습니다.");
			map.put("tio", tio);
			mv = new ModelAndView("jsonView","tio", map);
		}else{
			map.put("rect", "이미 추천한 게시물입니다");
			mv = new ModelAndView("jsonView","tio", map);
		}
		
		return mv;
	}
}
